package com.think.teaching.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.think.common.controller.BaseController;
import com.think.common.model.Result;
import com.think.common.model.ResultCode;
import com.think.common.utils.Common;
import com.think.teaching.model.*;
import com.think.teaching.service.VrmlTroomResService;
import com.think.teaching.service.VrmlTroomService;
import com.think.teaching.service.impl.*;
import com.think.teaching.utils.CourseState;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 章 前端控制器
 * </p>
 *
 * @author think
 * @since 2020-08-12
 */
@RestController
@RequestMapping("/v1")
@Api(tags =  "章接口文档")
public class ChapterController extends BaseController{
	private final Logger logger = LoggerFactory.getILoggerFactory().getLogger("");

	private final ChapterServiceImpl chapterService;
	private final CourseServiceImpl courseService;
	private final ArticleLessonServiceImpl articleLessService;
	private final VideoLessonServiceImpl videoLessonService;
	private final VrLessonServiceImpl vrLessonService;
	private final LivingLessonServiceImpl livingLessonService;

	private final VrmlTroomService vrmlTroomService;

	private final VrmlTroomResService vrmlTroomResService;


	public ChapterController(ChapterServiceImpl chapterService,
                             CourseServiceImpl courseService,
                             ArticleLessonServiceImpl articleLessService,
                             VideoLessonServiceImpl videoLessonService,
                             VrLessonServiceImpl vrLessonService,
                             LivingLessonServiceImpl livingLessonService, VrmlTroomService vrmlTroomService, VrmlTroomResService vrmlTroomResService) {
		this.chapterService = chapterService;
		this.courseService = courseService;
		this.articleLessService = articleLessService;
		this.videoLessonService = videoLessonService;
		this.vrLessonService = vrLessonService;
		this.livingLessonService = livingLessonService;
        this.vrmlTroomService = vrmlTroomService;
        this.vrmlTroomResService = vrmlTroomResService;
    }


	@ApiOperation("实训室添加新的实训室")
	@PostMapping("admin/chapter/addroom")
	public Result RoomAddNewShiXunRoom(@RequestBody()VrmlTroom data) {

		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			VrmlTroom vrmlTroom = vrmlTroomService.AddVrmlTroom(data);
			if( vrmlTroom!= null) {
				return Result.success(vrmlTroom);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	@ApiOperation("实训室更新实训室")
	@PostMapping("admin/chapter/updateroom")
	public Result RoomUpdateNewShiXunRoom(@RequestBody()VrmlTroom data) {

		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		VrmlTroom vrmlTroom = vrmlTroomService.getById(data.getId());
		if(vrmlTroom == null){
			return Result.failure(ResultCode.ROOM_NOT_EXIST);
		}

		if(result.getCode() == ResultCode.SUCCESS.code()) {
			if(vrmlTroomService.updateById(data)) {
				return Result.success();
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	@ApiOperation("删除实训室")
	@RequestMapping(value = "admin/chapter/delRoom/{id}",method = RequestMethod.POST)
	public Result DeleteRoom(@PathVariable("id")Integer id) throws ParseException {

		List<VrmlTroomRes> vrmlTroomResListNew = new ArrayList<>();
		VrmlTroom vrmlTroom = vrmlTroomService.getById(id);
		if( vrmlTroom== null) {
			return Result.failure(ResultCode.ROOM_NOT_EXIST);
		}
		else {
			// 查询该实训室是否已预定,删除
			List<VrmlTroomRes> vrmlTroomResList = vrmlTroomResService.list(new QueryWrapper<VrmlTroomRes>().eq("trainingroom_id",id));
			if(vrmlTroomResList.size()>0){
				for(VrmlTroomRes vrmlTroomRes : vrmlTroomResList){
					vrmlTroomResService.remove(new QueryWrapper<VrmlTroomRes>().eq("trainingroom_id",vrmlTroomRes.getTrainingroomId()));
				}
			}
			if (vrmlTroomService.removeById(id)) {
				return Result.success();
			}
			return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
		}
	}

	@ApiOperation("实训室获取实训室列表")
	@RequestMapping(value = "open/chapters/roomList/{page}/{count}",method = RequestMethod.GET)
	public Result RoomList(@PathVariable("page")Integer page,
						   @PathVariable("count")Integer count
			              ,@RequestParam(value = "type",required = false, defaultValue = "0") Integer type) {

		return Result.success(vrmlTroomService.RoomList(count, page, type, 0));
	}



	@ApiOperation("预定实训室")
	@PostMapping("admin/chapter/addroomres")
	public Result RoomAddNewShiXunRoomRes(@RequestBody()VrmlTroomRes data) {
		Result result = data.CheckObjectComplete();

		List<VrmlTroomRes> vrmlTroomResList = vrmlTroomResService.list(new QueryWrapper<VrmlTroomRes>().eq("created_by",Common.GetCurrentAuthor().getUserId())
				.eq("trainingroom_id",data.getTrainingroomId()).last("and type!= '0'"));
		if(vrmlTroomResList.size()>0){
			return Result.failure(ResultCode.ROOMRES_ALREADY_EXIST);
		}
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		data.setUpdatedBy(Common.GetCurrentAuthor().getUserId());
		VrmlTroom vrmlTroom = vrmlTroomService.getById(data.getTrainingroomId());
		if(vrmlTroom != null){
			data.setTrainingroomName(vrmlTroom.getName());
			data.setTrainingroomBody(vrmlTroom.getPosition());
			data.setStartDate(data.getReserveDate());
			data.setEndDate(data.getReserveDate());
		}

		// 查询是否已预定该实训室
		/*List<VrmlTroomRes> vrmlTroomResList = vrmlTroomResService.list(new QueryWrapper<VrmlTroomRes>().eq("trainingroom_id",data.getTrainingroomId()).eq("updated_by",Common.GetCurrentAuthor().getUserId()));
		if(vrmlTroomResList.size()>0){
			return Result.failure(ResultCode.ROOMRES_ALREADY_EXIST);
		}*/

		if(result.getCode() == ResultCode.SUCCESS.code()) {
			if(vrmlTroomResService.save(data)) {
				return Result.success();
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	@ApiOperation("我的预定")
	@PostMapping("admin/chapter/myroomres/{page}/{count}")
	public Result myroomres(@PathVariable("page")Integer page,@PathVariable("count")Integer count,@RequestParam(value = "flag",required = false) Integer flag) {

		return Result.success(vrmlTroomResService.RoomResList(Common.GetCurrentAuthor().getUserId(),count,page,flag,false));
//		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//		List<VrmlTroomRes> vrmlTroomResList = new ArrayList<VrmlTroomRes>();
		// flag,0管理员，1普通学生
		/*if("0".equals(flag)){
			vrmlTroomResList = vrmlTroomResService.list();
		}else{
			vrmlTroomResList = vrmlTroomResService.list(new QueryWrapper<VrmlTroomRes>().eq("updated_by",Common.GetCurrentAuthor().getUserId()));
		}

		if(vrmlTroomResList.size()>0){
			for(VrmlTroomRes vrmlTroomRes : vrmlTroomResList){
				VrmlTroom vrmlTroom = vrmlTroomService.getById(vrmlTroomRes.getTrainingroomId());
				Map<String,Object> map = new HashMap<>();
				map.put("id",vrmlTroomRes.getId());
				map.put("type",vrmlTroomRes.getType());
				map.put("trainingroomName",vrmlTroomRes.getTrainingroomName());
				map.put("trainingroomBody",vrmlTroomRes.getTrainingroomBody());
				map.put("trainingroomId",vrmlTroomRes.getTrainingroomId());
				map.put("reserveDate",vrmlTroomRes.getReserveDate());
				map.put("startDate",vrmlTroomRes.getStartDate());
				map.put("endDate",vrmlTroomRes.getEndDate());
				map.put("createdBy",vrmlTroomRes.getCreatedBy());
				map.put("createdTime",vrmlTroomRes.getCreatedTime());
				map.put("updatedBy",vrmlTroomRes.getUpdatedBy());
				map.put("updatedTime",vrmlTroomRes.getUpdatedTime());
				if(vrmlTroom != null){
					map.put("shixunshiName",vrmlTroom.getName());
					map.put("position",vrmlTroom.getPosition());
				}


				list.add(map);
			}
		}*/

//		return Result.success(list);
	}

	@ApiOperation("取消实训室预定")
	@RequestMapping(value = "admin/chapter/delRoomRes/{id}",method = RequestMethod.POST)
	public Result DeleteRoomRes(@PathVariable("id")Integer id) throws ParseException {
		if (vrmlTroomResService.removeById(id)) {
			return Result.success();
		}
		return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
	}

	@ApiOperation("预定实验室审核")
	@RequestMapping(value = "admin/chapter/audRoomRes/{id}/{type}",method = RequestMethod.POST)
	public Result AudRoomRes(@PathVariable("id")Integer id, @PathVariable("type") Integer type) throws ParseException {
		VrmlTroomRes vrmlTroomRes = vrmlTroomResService.getOne(new QueryWrapper<VrmlTroomRes>().eq("id",id));
		if(vrmlTroomRes != null){
			vrmlTroomRes.setType(String.valueOf(type));
			if (vrmlTroomResService.updateById(vrmlTroomRes)) {
				return Result.success();
			}
		}

		return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
	}




	@ApiOperation("添加新的章")
	@PostMapping("admin/chapter")
	public Result AddNewChapter(@RequestBody()Chapter data) {

		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			if (courseService.CheckCourseExist(data.getCourseId(),false) == null) {
				return Result.failure(ResultCode.COURSE_NOT_EXIST);
			}
			courseService.ChangeObjectState(data.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
			Chapter chapter = chapterService.AddChapter(data);
			if( chapter!= null) {
				return Result.success(chapter);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("更新章节")
	@RequestMapping(value = "admin/chapter",method = RequestMethod.PUT)
	public Result UpdateChapter(@RequestBody()Chapter data) {
		Result result = data.CheckObjectComplete();
		Chapter chapter = chapterService.getById(data.getId());
		if( chapter== null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			courseService.ChangeObjectState(data.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
			chapter = chapterService.UpdateChapter(data);
			if( chapter!= null) {
				return Result.success(chapter);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("删除章节")
	@RequestMapping(value = "admin/chapter/{id}",method = RequestMethod.DELETE)
	public Result DeleteChapter(@PathVariable("id")Integer id) {
		Chapter chapter = chapterService.getById(id);
		if( chapter== null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		else {
			if (chapterService.DeleteObjectById(id)) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success();
			}
			return Result.failure(ResultCode.SYSTEM_INNER_ERROR);
		}
	}
	
	@ApiOperation("管理员获取章节详情")
	@RequestMapping(value = "admin/chapter/{id}",method = RequestMethod.GET)
	public Result GetChapter(@PathVariable("id")Integer id) {
		Chapter chapter = chapterService.GetChapter(id);
		if( chapter== null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		else {
			
			return Result.success(chapter);
		}
	}
	
	@ApiOperation("用户获取章节详情")
	@RequestMapping(value = "open/chapter/{id}",method = RequestMethod.GET)
	public Result UserGetChapter(@PathVariable("id")Integer id) {
		Chapter chapter = chapterService.GetChapter(id);
		if( chapter== null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		else {
			Map<String,Object> map = new HashMap<>();
			Map<String,Object> map1 = new HashMap<>();
			map.put("createdBy",chapter.getCreatedBy());
			map.put("createdTime",chapter.getCreatedTime());
			map.put("updatedBy",chapter.getUpdatedBy());
			map.put("updatedTime",chapter.getUpdatedTime());
			map.put("delflag",chapter.getDelflag());
			map.put("state",chapter.getState());
			map.put("id",chapter.getId());
			map.put("courseId",chapter.getCourseId());
			map.put("chapterName",chapter.getChapterName());
			map.put("lessonType",chapter.getLessonType());
			map.put("index",chapter.getIndex());
			map1.put("projUrl",chapter.getLessonDetails().get("projUrl"));
			map1.put("principle",chapter.getLessonDetails().get("principle"));
			map1.put("typeName",chapter.getLessonDetails().get("typeName"));
			map1.put("description",chapter.getLessonDetails().get("description"));
			map1.put("deviceRequire",chapter.getLessonDetails().get("deviceRequire"));
			map1.put("expImg",chapter.getLessonDetails().get("expImg"));
			map1.put("duration",chapter.getLessonDetails().get("duration"));
			map1.put("score",chapter.getLessonDetails().get("score"));
			map1.put("chapterId",chapter.getLessonDetails().get("chapterId"));
			map1.put("contact",chapter.getLessonDetails().get("contact"));
			map1.put("createdTime",chapter.getLessonDetails().get("createdTime"));
			map1.put("id",chapter.getLessonDetails().get("id"));
			map1.put("state",chapter.getLessonDetails().get("state"));
			map1.put("courseId",chapter.getLessonDetails().get("courseId"));
			map1.put("delflag",chapter.getLessonDetails().get("delflag"));
			map1.put("introduction",chapter.getLessonDetails().get("introduction"));
			map1.put("expGuide",chapter.getLessonDetails().get("expGuide"));
			map1.put("updatedTime",chapter.getLessonDetails().get("updatedTime"));
			map1.put("expName",chapter.getLessonDetails().get("expName"));
			map1.put("updatedBy",chapter.getLessonDetails().get("updatedBy"));
			map1.put("servicePlan",chapter.getLessonDetails().get("servicePlan"));
			map1.put("expFeature",chapter.getLessonDetails().get("expFeature"));
			map1.put("createdBy",chapter.getLessonDetails().get("createdBy"));
			map1.put("expExam",chapter.getLessonDetails().get("expExam"));
			map1.put("introduceVideo",chapter.getLessonDetails().get("introduceVideo"));
			map1.put("guideVideo",chapter.getLessonDetails().get("guideVideo"));
			map1.put("stepCount",chapter.getLessonDetails().get("stepCount"));
			String exeUrl = String.valueOf(chapter.getLessonDetails().get("exeUrl"));
			if(StringUtils.isNullOrEmpty(exeUrl) || "null".equals(exeUrl)){
				map1.put("exeUrl","");
			}else{
				map1.put("exeUrl",chapter.getLessonDetails().get("exeUrl"));
			}

			map.put("lessonDetails",map1);
			return Result.success(map);
		}
	}
	
	@ApiOperation("管理员修改章节状态")
	@RequestMapping(value = "admin/chapter/{id}/{state}",method = RequestMethod.PUT)
	public Result UpdateChapterState(@PathVariable("id")Integer id,@PathVariable("state")Integer state) {
		Chapter chapter = chapterService.getById(id);
		if( chapter!= null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		else {
			try {
				chapter = chapterService.SetChapterState(id, state);
				return Result.success(chapter);
			} catch (Exception e) {
				return Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}
	}
	
	@ApiOperation("用户搜索章节")
	@RequestMapping(value = "user/chapter/search",method = RequestMethod.GET)
	public Result UserSearchChapter(@RequestParam("key")String key) {
		return Result.success(chapterService.ListChapterSearch(key, true));
	}
	
	@ApiOperation("管理员搜索章节")
	@RequestMapping(value = "admin/chapter/search",method = RequestMethod.GET)
	public Result AdminSearchChapter(@RequestParam("key")String key) {
		return Result.success(chapterService.ListChapterSearch(key, false));
	}
	
	@ApiOperation("管理员获取章节列表")
	@RequestMapping(value = "admin/chapters/{page}/{count}",method = RequestMethod.GET)
	public Result AdminListChapter(@PathVariable("page")Integer page,@PathVariable("count")Integer count,@RequestParam(value = "type",required = false,defaultValue = "0") Integer type) {
		return Result.success(chapterService.ListChapterWithTagAndType(count, page, type, 0, false));
	}
	
	@ApiOperation("用户获取章节列表")
	@RequestMapping(value = "user/chapters/{page}/{count}",method = RequestMethod.GET)
	public Result UserListChapter(@PathVariable("page")Integer page,@PathVariable("count")Integer count,@RequestParam(value = "type",required = false,defaultValue = "0") Integer type) {
		return Result.success(chapterService.ListChapterWithTagAndType(count, page, type, 0, true));
	}
	
	
	@ApiOperation("添加章节课程详情-文章")
	@PostMapping("admin/chapter/article")
	public Result AddChapterArticleDetails(@RequestBody()ArticleLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.ARTICLE_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			if(chapterService.getBaseMapper().getLessonDetails(data.getChapterId(), Chapter.ARTICLE_CHAPTER) != null) {
				return Result.failure(ResultCode.CHAPTER_ALREADY_LESSON);
			}
			ArticleLesson lesson = articleLessService.AddArticleLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("添加章节课程详情-虚拟仿真实验")
	@PostMapping("admin/chapter/vr")
	public Result AddChapterVRDetails(@RequestBody()VrLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.VR_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			if(chapterService.getBaseMapper().getLessonDetails(data.getChapterId(), Chapter.VR_CHAPTER) != null) {
				return Result.failure(ResultCode.CHAPTER_ALREADY_LESSON);
			}
			VrLesson lesson = vrLessonService.AddVrLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("添加章节课程详情-视频课程")
	@PostMapping("admin/chapter/video")
	public Result AddChapterVideoDetails(@RequestBody()VideoLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.VIDEO_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			if(chapterService.getBaseMapper().getLessonDetails(data.getChapterId(), Chapter.VIDEO_CHAPTER) != null) {
				return Result.failure(ResultCode.CHAPTER_ALREADY_LESSON);
			}
			VideoLesson lesson = videoLessonService.AddVideoLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("添加章节课程详情-直播课程")
	@PostMapping("admin/chapter/living")
	public Result AddChapterLivingDetails(@RequestBody()LivingLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.LIVING_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			if(chapterService.getBaseMapper().getLessonDetails(data.getChapterId(), Chapter.LIVING_CHAPTER) != null) {
				return Result.failure(ResultCode.CHAPTER_ALREADY_LESSON);
			}
			LivingLesson lesson = livingLessonService.AddLivingLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("更新章节课程详情-文章")
	@PutMapping("admin/chapter/article")
	public Result UpdateChapterArticleDetails(@RequestBody()ArticleLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.ARTICLE_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			ArticleLesson lesson = articleLessService.UpdateArticleLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}

	@ApiOperation("更新章节课程详情-虚拟仿真实验")
	@PutMapping("admin/chapter/vr")
	public Result UpdateChapterVRDetails(@RequestBody()VrLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.VR_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			VrLesson lesson = vrLessonService.UpdateVrLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("更新章节课程详情-视频课程")
	@PutMapping("admin/chapter/video")
	public Result UpdateChapterVideoDetails(@RequestBody()VideoLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.VIDEO_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			VideoLesson lesson = videoLessonService.UpdateVideoLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	@ApiOperation("更新章节课程详情-直播课程")
	@PutMapping("admin/chapter/living")
	public Result UpdateChapterLivingDetails(@RequestBody()LivingLesson data) {
		Result result = data.CheckObjectComplete();
		data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		
		if(result.getCode() == ResultCode.SUCCESS.code()) {
			Chapter chapter = chapterService.CheckChapterExist(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getLessonType() != Chapter.LIVING_CHAPTER) {
				return Result.failure(ResultCode.LESSON_NOT_MATCH_CHAPTER);
			}
			LivingLesson lesson = livingLessonService.UpdateLivingLesson(data);
			if( lesson!= null) {
				courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
				return Result.success(lesson);
			}
			else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}
		}
		else
			return result;
	}
	
	
	@ApiOperation("删除当前章节下的章节内容")
	@DeleteMapping("admin/chapter/lesson/{chapterId}")
	public Result DeleteChapterLivingDetails(@PathVariable("chapterId")Integer chapterId) {
		
		Chapter chapter = chapterService.GetChapter(chapterId);
		if (chapter == null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		else if (chapter.getLessonDetails() == null) {
			return Result.failure(ResultCode.CHAPTER_NO_LESSON);
		}
		courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());

		return Result.success(chapterService.DeleteLesson(chapterId,chapter.getLessonType()));
	}
	
	@ApiOperation("修改当前章下的章节课程状态")
	@PostMapping("admin/chapter/lesson/{chapterId}")
	public Result DeleteChapterLivingDetails(@PathVariable("chapterId")Integer chapterId, @RequestParam() Integer state) {
		
		Chapter chapter = chapterService.GetChapter(chapterId);
		if (chapter == null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		else if (chapter.getLessonDetails() == null) {
			return Result.failure(ResultCode.CHAPTER_NO_LESSON);
		}
		courseService.ChangeObjectState(chapter.getCourseId(), CourseState.WAITING_SUBMIT.getValue());
		return Result.success(chapterService.ChangeLessonState(chapterId, chapter.getLessonType(),state));
	}
	
	@ApiOperation("修改当前章节下的章节内容的状态")
	@PostMapping("admin/chapter/move/{chapterId}")
	public Result MoveUpChapter(@PathVariable("chapterId")Integer id,@RequestParam()Integer dir) {
		Chapter chapter = chapterService.GetChapter(id);
		if (chapter == null) {
			return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
		}
		if (chapterService.MoveChapter(chapter, dir>0)) {
			return Result.success();
		}
		else {
			return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
		}
	}

	
	
}

